import { chunk, omit } from 'lodash';

type TNewRecord = {
  devices: Record<string, any>[];
  [key: string]: any;
};

export function transformStatisticMultiObjectResponse(
  res: {
    data: {
      total?: number;
      records: Record<string, any>[];
    };
  },
  params: {
    codes: string[];
  } & API.PageParams,
  keysToMap: string[],
) {
  const newTotal = Math.ceil((res.data?.total ?? 0) / params.codes.length);
  // 将records按照对象数量进行chunk分组
  const newRecords = chunk(res.data?.records, params.codes.length).map((chunk) => {
    const newRecordItem: {
      devices: Record<string, any>[];
      [key: string]: any;
    } = {
      devices: [],
      ...omit(chunk[0], keysToMap),
    };

    return chunk
      .sort((a, b) => (a.deviceName ?? '').localeCompare(b.deviceName ?? ''))
      .reduce<TNewRecord>((acc, cur, index) => {
        acc.devices.push(cur);
        keysToMap.forEach((key) => {
          acc[`${key}${index + 1}`] = cur[key];
        });
        return acc;
      }, newRecordItem);
  });

  const newRes = {
    ...res,
    data: {
      ...res.data,
      total: newTotal,
      records: newRecords,
      pageSize: params.pageSize!,
    },
  };

  return newRes;
}
